
import 'package:flutter/material.dart';
import 'package:myapp/util/PageUtil.dart';

class SearchBarDelegate extends SearchDelegate<String> {
  SearchBarDelegate() : super(searchFieldLabel: "请输入产品名");

  ///================= 模拟后台数据 ========================
  List<String> nameList = [
    '口罩',
    '袜子',
    '手机',
    '电脑',
    '洗衣机',
    '电视机',
    '卧室',
    '厨房',
    '卫生间',
    '客厅'
  ];

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: Icon(Icons.clear),
        onPressed: () {
          query = "";
          showSuggestions(context);
        },
      ),
      IconButton(
        icon: Icon(Icons.search),
        onPressed: () {
          //跳往搜索结果页面
          PageUtil.toSearchResultPage(context, query);
        },
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: AnimatedIcon(
          icon: AnimatedIcons.menu_arrow, progress: transitionAnimation),
      onPressed: () {
        if (query.isEmpty) {
          close(context, null);
        } else {
          query = "";
          showSuggestions(context);
        }
      },
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return null;
  }

  // 输入时的推荐及搜索结果
  @override
  Widget buildSuggestions(BuildContext context) {
    return Wrap(
      spacing: 7,
      runSpacing: 4,
      children: hotNameList(context),
    );
  }

  List<Widget> hotNameList(BuildContext context) {
    List<Widget> widgetList = List();
    for (int i = 0; i < nameList.length; i++) {
      Widget widget = GestureDetector(
        child: Container(
          margin: const EdgeInsets.all(10),
          padding: const EdgeInsets.all(10),
          // 盒子样式
          decoration: new BoxDecoration(
              color: Colors.blueAccent,
              //设置Border属性给容器添加边框
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Text(
            nameList[i],
            style: TextStyle(color: Colors.white),
          ),
        ),
        onTap: () {
          query = nameList[i];
          PageUtil.toSearchResultPage(context, query);
        },
      );
      widgetList.add(widget);
    }
    return widgetList;
  }

  @override
  ThemeData appBarTheme(BuildContext context) {
    // TODO: implement appBarTheme
    ThemeData appBarTheme(BuildContext context) {
      assert(context != null);
      final ThemeData theme = Theme.of(context);
      assert(theme != null);
      return theme.copyWith(
        primaryColor: Colors.white,
        primaryIconTheme: theme.primaryIconTheme.copyWith(color: Colors.grey),
        primaryColorBrightness: Brightness.light,
        primaryTextTheme: theme.textTheme,
      );
    }

    return appBarTheme(context);
  }

}
